﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Coder.Workflow;
using Coder.Workflow.Stores;
using Identity;
using Microsoft.EntityFrameworkCore;

namespace Fee.Orders
{
    internal static class SearchExtentions
    {
        public static IQueryable<WorkActivity> IncludeAllDelegateBase<T>(this IWorkActivityStore<T> _workActivityStore, IQueryable<WorkActivity> query)
        where T : FeeDbContext
        {

            return _workActivityStore.InclideAll(query)
                .Include(f => (DelegateOrderBase)f.ProcessInstance).ThenInclude(f => f.ConstructionTask).ThenInclude(f => f.Station).ThenInclude(f => f.District)
                .Include(f => (DelegateOrderBase)f.ProcessInstance).ThenInclude(f => f.ConstructionTask).ThenInclude(f => f.Station).ThenInclude(f => f.OrderDistrict);

        }

        public static IQueryable<WorkActivity> ForDelegateBase(this DelegateWorkActivitySearch searcher, FeeDbContext _context)
        {
            var roleIds = searcher.Roles.Select(f => f.Id);
            bool isDelegateRole = roleIds.Contains(_context.DelegateAdminId()) || roleIds.Contains(_context.AdminRoleId());
            var query = _context.WorkActivities
                .Where(workActivity =>
                    (isDelegateRole || (workActivity.DepositUser == null && roleIds.Contains(workActivity.Role.Id)) || searcher.UserId == workActivity.DepositUser.Id)
                    && (searcher.Statuses == null || searcher.Statuses.Contains(workActivity.Status))
                    && (searcher.WorkTask == null || workActivity.WorkTask.Name == searcher.WorkTask)
                    && (searcher.ProcessType == null || searcher.ProcessType.Contains(workActivity.ProcessInstance.WorkProcess.WorkflowType))
                    && (searcher.Station == null || searcher.Station.Name == null || searcher.Station.Name == ((DelegateOrderBase)workActivity.ProcessInstance).ConstructionTask.Station.Name)
                    && (searcher.Station == null || searcher.Station.District == null || searcher.Station.District.Id == ((DelegateOrderBase)workActivity.ProcessInstance).ConstructionTask.Station.District.Id)
                    && (searcher.Station == null || searcher.Station.OrderDistrict == null || searcher.Station.District.Id == ((DelegateOrderBase)workActivity.ProcessInstance).ConstructionTask.Station.OrderDistrict.Id)
                    && (searcher.Station == null || searcher.Station.Status == null || ((DelegateOrderBase)workActivity.ProcessInstance).ConstructionTask.Station.Status == searcher.Station.Status.Value)
                    && (searcher.Station == null || searcher.Station.Type == null || ((DelegateOrderBase)workActivity.ProcessInstance).ConstructionTask.Station.Type == searcher.Station.Type.Value)


                );
            return query;
        }
    }
}
